<template>
    <div class="upload-container">
        <el-upload class="upload-demo" action="http://127.0.0.1:8000/api/upload/" <!-- 替换为你的后端上传接口 -->
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            :before-upload="beforeUpload"
            :show-file-list="true"
            list-type="picture-card"
            >
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>

        <!-- 预览弹窗 -->
        <el-dialog v-model="dialogVisible" title="图片预览" width="50%">
            <img v-if="previewUrl" :src="previewUrl" alt="图片预览" class="preview-image" />
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
    import { ref } from "vue";
    import { ElMessage, ElDialog } from "element-plus";
    import { Plus } from "@element-plus/icons-vue";

    const dialogVisible = ref(false);
    const previewUrl = ref("");

    // 预览图片
    const handlePreview = (file: any) => {
        previewUrl.value = file.url || URL.createObjectURL(file.raw);
        dialogVisible.value = true;
    };

    // 上传成功回调
    const handleSuccess = (response: any) => {
        if (response.code === 200) {
            ElMessage.success("上传成功！");
        } else {
            ElMessage.error("上传失败，请重试！");
        }
    };

    // 上传前校验（文件大小和格式）
    const beforeUpload = (file: File) => {
        const isImage = file.type.startsWith("image/");
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isImage) {
            ElMessage.error("只能上传图片格式文件！");
            return false;
        }
        if (!isLt2M) {
            ElMessage.error("图片大小不能超过 2MB！");
            return false;
        }
        return true;
    };
</script>

<style scoped>
    .upload-container {
        text-align: center;
    }

    .preview-image {
        width: 100%;
        height: auto;
        display: block;
    }
</style>